[Java] 使用DateTimeFormatterBuilder 解析日期字串


Posted by yaweichiang on 2022-11-26

在後端呼叫第三方API時取得的日期時間字串格式如下:/Date(xxxxxxxxxxxxx+xxxx)/
需要將日期時間字串轉換成以下格式:yyyy-MM-ddTHH:mm:ss

使用DateTimeFormatterBuilder建立符合原始字串的Formatter,用來將原始字串parse成相應LocalDateTime物件
再將LocalDateTime物件透過目標格式的Formatter格式化成我們所想要的日期時間格式字串

DateTimeFormatter jsonDateTimeFormatter = new DateTimeFormatterBuilder()
                .appendLiteral("/Date(")
                .appendValue(ChronoField.INSTANT_SECONDS)
                .appendValue(ChronoField.MILLI_OF_SECOND,3)
                .appendOffset("+HHmm","+0000")
                .appendLiteral(")/")
                .toFormatter();

DateTimeFormatter targetDateTimeFormatter = DateTiemFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
@JsonProperty("startDate")
private String startDate;

public void setStartDate(String startDate){
    if(startDate.matches("^\\/Date\\(\\d{13,13}\\+\\d{4,4}\\)\\/$")){
        LocalDatetime dateTime = LocalDateTime.parse(startDate,jsonDateTimeFormatter);
        startDate = dateTime.format(targetDateTimeFormatter);
    }
    this.startDate = startDate;
}

#java #DateTimeFormat #JsonDate







Related Posts

ASP.NET Core Web API 入門教學 - 同時取得父子資料

ASP.NET Core Web API 入門教學 - 同時取得父子資料

How to solve the perpetual loading issue in Evernote? Evernote 一直轉圈圈的解決辦法

How to solve the perpetual loading issue in Evernote? Evernote 一直轉圈圈的解決辦法

JS30 Day 15 筆記

JS30 Day 15 筆記


Comments